/* eslint-disable react/jsx-key */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useRef, useMemo } from 'react';
import ReactDOM from 'react-dom';
import { Image, Switch, Button, Modal, message, Popconfirm, Tooltip } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { area, user, classify } from '@/services/basic';
import { connect } from 'umi';
import { PlusOutlined, TagFilled } from '@ant-design/icons';
import { doFetch, getFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import moment from 'moment';
import CompanyName from '@/components/CompanyName';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

let defaultFields = {
  feedback_describe: {
    value: null,
    type: 'textarea',
    title: '任务描述',
    name: ['feedback_describe'],
    required: true,
    col: {
      span: 24,
    },
  },
  is_completed: {
    value: null,
    type: 'radio',
    title: '是否完成',
    name: ['is_completed'],
    required: true,
    options: [
      {
        label: '完成',
        value: true,
      },
      {
        label: '未完成',
        value: false,
      },
    ],
    col: {
      span: 24,
    },
  },
};

const obj = {
    customer_name: '联系人',
    classify_name: '公司类型',
    receive_order_user_name: '接单人',
    customer_phone: '联系人手机号',
    account_user_name: '记账会计',
    finance_mainer_name: '会计主管',
    unit_price: '月收费',
  },
  objs = {
    customer_name: { show: false },
    classify_name: { show: false },
    receive_order_user_name: { show: false },
    customer_phone: { show: false },
    account_user_name: { show: false },
    finance_mainer_name: { show: false },
    unit_price: { show: false },
  };

function Daily(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [type, ctype] = useState('1'),
    [iftype, ciftype] = useState({});

  let actionRef = useRef(),
    ChildRef = null;

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  const { data } = useRequest(async () => {
    let unnum = await getFetch({ url: '/wbn-api/daily_work/un_complete_amount' });
    let unnums = await getFetch({ url: '/wbn-api/payment_work/un_complete_amount' });
    let result = await getFetch({ url: '/wbn-api/work_level', params: { is_all: 1 } });
    return {
      unnum: unnum?.data,
      unnums: unnums?.data,
      workTypeLevel: result?.data,
    };
  });

  const tabList = [
    {
      key: '1',
      tab: `日常事项(待处理${data?.unnum ?? '-'})`,
    },
    {
      key: '2',
      tab: `收款事项(待处理${data?.unnums ?? '-'})`,
    },
  ];

  const columns = useMemo(() => {
    const arrs = Object.keys(obj)?.map((it) => {
      return {
        title: obj[it],
        dataIndex: it,
        key: it,
        search: false,
      };
    });
    if (type === '1') {
      return [
        {
          title: '公司编号',
          dataIndex: 'company_code',
          key: 'company_code',
        },
        {
          title: '公司名称',
          dataIndex: 'company_name',
          key: 'company_name',
          render: (_, row) => (
            <CompanyName
              row={{ ...row, name: row?.company_name ?? row.name, id: row?.company_id ?? row.id }}
              reload={reload}
            />
          ),
        },
        {
          title: '区域',
          dataIndex: 'area_name',
          key: 'area_id',
          valueType: 'select',
          options: {
            database: area,
            params: {
              is_all: 1,
            },
          },
        },
        {
          title: '办事类型',
          dataIndex: 'work_type_name',
          key: 'work_type_id',
          valueType: 'select',
          options: {
            database: (params) => getFetch({ url: '/wbn-api/work_type', params }),
            params: { is_all: 1 },
          },
        },
        {
          title: '重要程度',
          dataIndex: 'work_type_level',
          key: 'work_type_level',
          search: false,
          render: (text, row) => {
            let res = data?.workTypeLevel?.filter?.((it) => it?.type === row?.work_type_level);

            return res?.[0]?.name ?? '-';
          },
        },
        {
          title: '办理期限（天）',
          dataIndex: 'limit_day',
          key: 'limit_day',
          search: false,
        },
        {
          title: '任务描述',
          dataIndex: 'task_describe',
          key: 'task_describe',
          search: false,
        },
        {
          title: '经办人',
          dataIndex: 'user_name',
          key: 'user_name',
        },
        {
          title: '创建时间-开始',
          dataIndex: 'start_date',
          key: 'start_date',
          hideInTable: true,
          valueType: 'date',
        },
        {
          title: '创建时间-结束',
          dataIndex: 'end_date',
          key: 'end_date',
          hideInTable: true,
          valueType: 'date',
        },
        {
          title: '创建时间',
          dataIndex: 'created_at',
          key: 'created_at',
          search: false,
          render: (_text, row) => {
            const text = row.created_at;
            return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-';
          },
        },
        {
          title: '剩余天数',
          dataIndex: 'remaining_day',
          key: 'remaining_day',
        },

        {
          title: '创建人',
          dataIndex: 'creator_name',
          key: 'creator_name',
          search: false,
        },
        {
          title: '反馈人',
          dataIndex: 'feedback_user_name',
          key: 'feedback_user_name',
          search: false,
        },
        {
          title: '反馈时间',
          dataIndex: 'feedback_time',
          key: 'feedback_time',
          search: false,
          render: (text, record) => {
            return record?.feedback_time
              ? moment(record?.feedback_time).format('YYYY-MM-DD HH:mm:ss')
              : '-';
          },
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          valueType: 'select',
          options: [
            {
              value: 'normal',
              label: '进行中',
            },
            {
              value: 'delay',
              label: '延期',
            },
            {
              value: 'un_completed',
              label: '未办结',
            },
            {
              value: 'completed',
              label: '已完成',
            },
          ],
          render: (text, row) => {
            const cofs = {
              normal: '进行中',
              delay: '延期',
              un_completed: '未完成',
              completed: '已完成',
            };
            return (
              <div className="centerl" style={{ gap: 12 }}>
                {cofs[row?.status]}
                {row?.feedback_describe && ['un_completed', 'completed']?.includes(row?.status) && (
                  <TagFilled
                    style={{ color: '#1890ff' }}
                    onClick={() => {
                      Modal.info({
                        title: '反馈信息',
                        content: row?.feedback_describe,
                      });
                    }}
                  />
                )}
              </div>
            );
          },
        },
        ...arrs,
        // {
        //   title: '操作',
        //   valueType: 'option',
        //   width: 180,
        //   render: (text, record, _, action) => [
        //     <Popconfirm
        //       key={1}
        //       placement="bottom"
        //       title={'确认删除该办事类型？'}
        //       onConfirm={() => {
        //         doFetch({
        //           url: '/wbn-api/daily_work/' + record?.id,
        //           params: {},
        //           method: 'DELETE',
        //         }).then((res) => {
        //           if (res.code == 0) {
        //             message.success('操作成功');
        //             reload();
        //           }
        //         });
        //       }}
        //       okText="删除"
        //       cancelText="取消"
        //     >
        //       <a style={{ color: '#f50' }}>删除</a>
        //     </Popconfirm>,
        //     record.status === 'delay' || record.status === 'un_completed' ? (
        //       <a
        //         onClick={() => {
        //           cvs(true);
        //           cf(() => {
        //             for (let i in daily) {
        //               daily[i].value = record[i];
        //             }
        //             return { ...daily };
        //           });
        //           ciftype({
        //             val: 'reedit',
        //             title: '重新编辑任务',
        //             id: record.id,
        //             item: record,
        //           });
        //         }}
        //       >
        //         重新编辑
        //       </a>
        //     ) : null,
        //     record.status === 'normal' && (
        //       <a
        //         onClick={() => {
        //           cvs(true);
        //           cf((fields) => {
        //             for (let i in defaultFields) {
        //               defaultFields[i].value = null;
        //             }
        //             return { ...defaultFields };
        //           });
        //           ciftype({
        //             val: 'reply',
        //             title: '反馈',
        //             id: record?.id,
        //           });
        //         }}
        //       >
        //         反馈
        //       </a>
        //     ),
        //   ],
        // },
      ];
    } else {
      return [
        {
          title: '公司编号',
          dataIndex: 'company_code',
          key: 'company_code',
        },
        {
          title: '公司名称',
          dataIndex: 'company_name',
          key: 'company_name',
          render: (_, row) => (
            <CompanyName
              row={{ ...row, name: row?.company_name ?? row.name, id: row?.company_id ?? row.id }}
              reload={reload}
            />
          ),
        },
        {
          title: '区域',
          dataIndex: 'area_name',
          key: 'area_name',
          valueType: 'select',
          options: {
            database: area,
            params: {
              is_all: 1,
            },
          },
        },
        {
          title: '收款类型',
          dataIndex: 'payment_work_type_name',
          key: 'payment_work_type_name',
          valueType: 'select',
          options: {
            database: (params) => getFetch({ url: '/wbn-api/payment_work_type', params }),
            params: { is_all: 1 },
          },
        },
        {
          title: '收款性质',
          dataIndex: 'payment_nature',
          key: 'payment_nature',
          search: false,
          render: (text, row) => {
            let cofs = {
              normal: '进行中',
              delay: '逾期',
            };
            return cofs[row?.payment_nature] ?? '-';
          },
        },
        {
          title: '办理期限（天）',
          dataIndex: 'limit_day',
          key: 'limit_day',
          search: false,
        },
        {
          title: '任务描述',
          dataIndex: 'task_describe',
          key: 'task_describe',
          search: false,
        },
        {
          title: '经办人',
          dataIndex: 'user_name',
          key: 'user_name',
        },
        {
          title: '创建时间-开始',
          dataIndex: 'start_date',
          key: 'start_date',
          hideInTable: true,
          valueType: 'date',
        },
        {
          title: '创建时间-结束',
          dataIndex: 'end_date',
          key: 'end_date',
          hideInTable: true,
          valueType: 'date',
        },
        {
          title: '创建时间',
          dataIndex: 'created_at',
          key: 'created_at',
          search: false,
          render: (_text, row) => {
            const text = row.created_at;
            return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-';
          },
        },
        {
          title: '剩余天数',
          dataIndex: 'remaining_day',
          key: 'remaining_day',
        },
        {
          title: '创建人',
          dataIndex: 'creator_name',
          key: 'creator_name',
          search: false,
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          valueType: 'select',
          options: [
            {
              value: 'normal',
              label: '进行中',
            },
            {
              value: 'delay',
              label: '延期',
            },
            {
              value: 'un_completed',
              label: '未办结',
            },
            {
              value: 'completed',
              label: '已完成',
            },
          ],
          render: (text, row) => {
            const cofs = {
              normal: '进行中',
              delay: '延期',
              un_completed: '未完成',
              completed: '已完成',
            };
            return (
              <div className="centerl" style={{ gap: 12 }}>
                {cofs[row?.status]}
                {row?.feedback_describe && ['un_completed', 'completed']?.includes(row?.status) && (
                  <TagFilled
                    style={{ color: '#1890ff' }}
                    onClick={() => {
                      Modal.info({
                        title: '反馈信息',
                        content: row?.feedback_describe,
                      });
                    }}
                  />
                )}
              </div>
            );
          },
        },
        ...arrs,
      ];
    }
  }, [type, data]);

  let saveData = (values) => {
    if (iftype.val === 'reply') {
      doFetch({
        url: '/wbn-api/daily_work/handle_feedback',
        params: { ...values, id: iftype.id },
        method: 'PUT',
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val === 'replys') {
      doFetch({
        url: '/wbn-api/payment_work/handle_feedback',
        params: { ...values, id: iftype.id },
        method: 'PUT',
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val === 'reedit') {
      doFetch({
        url: '/wbn-api/daily_work/' + iftype.id,
        params: { ...values, company_id: iftype.item.company_id },
        method: 'PUT',
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val === 'reedits') {
      doFetch({
        url: '/wbn-api/payment_work/' + iftype.id,
        params: { ...values, company_id: iftype.item.company_id },
        method: 'PUT',
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  const [columnsStateMap, setColumnsStateMap] = useState(objs);

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        // pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path={type === '1' ? '/wbn-api/daily_work' : '/wbn-api/payment_work'}
        tabList={tabList}
        onTabChange={(key) => {
          ctype(key);
        }}
        columnsStateMap={columnsStateMap}
        setColumnsStateMap={setColumnsStateMap}

        // withCard={false}
        // cardtitle = "name" //卡片标题
        // cardavatar = "img_url" //卡片头像
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={600}
        destroyOnClose={true}
      >
        <InitForm
          fields={fields}
          submitData={(values) => {
            saveData(values);
          }}
          onChange={(changedValues, allValues) => {
            //联动操作
          }}
          submitting={props.loading.effects['basic/addpayment'] || !vs}
        />
      </Modal>
    </div>
  );
}

export default connect(({ basic, loading }) => ({
  basic,
  loading,
}))(Daily);
